<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      title="外购物料信息"
      :width="'70%'"
      class="allocation-dialog"
      :close-on-click-modal="false"
    >
      <div>
        <el-tabs v-model="activeLevel" class="level-tabs">
          <el-tab-pane name="in">
            <el-table :data="totalEnergyData" border class="allocation-table">
              <el-table-column prop="name" />
              <el-table-column prop="value" />
            </el-table>
            <!-- <el-empty v-else description="暂无数据" /> -->
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 底部按钮区域 -->
      <template #footer>
        <span class="dialog-footer">
          <template v-if="!isInputMode">
            <el-button @click="dialogVisible = false" type="primary">确认</el-button>
          </template>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import { Material } from "@/api/interface";

const dialogVisible = ref(false);
const isInputMode = ref(false);
const currentPCF = ref();
const baseUrl = import.meta.env.VITE_BASE_URL;
const loading = ref(false); // 加载状态
const materialDetail = ref<Partial<Material.ResMaterial>>(); // 新增材料详情数据

/**
 * 当前选中的层次
 */
const activeLevel = ref("");

// 获取第一个可见的 tab
const getFirstVisibleTab = computed(() => {
  return "in"; // 默认显示tab
});

// 自制数据展示
const totalEnergyData = computed(() => {
  let result = [];
  result.push({ name: "材料id", value: currentPCF.value.id });
  if (materialDetail.value) {
    result.push({ name: "材料名称", value: materialDetail.value.materialName });
    if (materialDetail.value.materialType === 1) {
      result.push({ name: "材料类型", value: "零件" });
    } else if (materialDetail.value.materialType === 2) {
      result.push({ name: "材料类型", value: "部件" });
    } else {
      result.push({ name: "材料类型", value: "原材料" });
    }
  }
  result.push({ name: "PCF值", value: currentPCF.value.pcf + " kgCO₂eq" });
  return result;
});

const fetchMaterialDetail = async (materialId: string | number) => {
  if (!materialId) {
    console.error("材料ID为空");
    return;
  }

  loading.value = true;
  try {
    const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
    const userId = Number(userInfo.id) || 0; // 如果没有 id，则使用默认值 0
    const response = await axios.post(`${baseUrl}/api/carbon/getMaterialById?materialId=${materialId}`, {
      userId: userId
    });
    if (response.data && response.data.code === 200) {
      materialDetail.value = response.data.data || {};
    } else {
      ElMessage.error(response.data?.msg || "获取材料详情失败");
      materialDetail.value = {};
    }
  } catch (error) {
    console.error("获取材料详情错误:", error);
    ElMessage.error("获取材料详情出错，请稍后重试");
    materialDetail.value = {};
  } finally {
    loading.value = false;
  }
};

// 打开对话框方法
const openDialog = async (PCF: any) => {
  currentPCF.value = PCF || {};
  if (PCF && PCF.outmaterialId) {
    await fetchMaterialDetail(PCF.outmaterialId);
  }
  activeLevel.value = getFirstVisibleTab.value;
  dialogVisible.value = true;
};

// 暴露方法给父组件
defineExpose({
  openDialog
});
</script>

<style scoped>
.allocation-dialog :deep(.el-dialog) {
  position: relative !important;
  top: 10vh !important;
  display: flex;
  flex-direction: column;
  height: 600px !important;
}

/* 录入模式时调整位置 */
.allocation-dialog :deep(.el-dialog)[aria-label="分配数据管理"] {
  top: 5vh !important;
}
.allocation-dialog :deep(.el-dialog__header) {
  padding: 15px 20px;
  margin: 0;
  border-bottom: 1px solid #dcdfe6;
}
.allocation-dialog :deep(.el-dialog__footer) {
  padding: 15px 20px;
  border-top: 1px solid #dcdfe6;
}
.allocation-dialog :deep(.el-tabs) {
  display: flex;
  flex-direction: column;
}
.allocation-dialog :deep(.el-tabs__content) {
  flex: 1;
}
.allocation-dialog :deep(.el-tab-pane) {
  padding: 20px 0;
}
.allocation-table {
  width: 100%;
}
.level-tabs {
  margin-bottom: 20px;
}
.dialog-footer {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}
.info-bar {
  display: flex;
  justify-content: space-around;
  padding: 10px 0;
  margin: 20px 0;
  background-color: #f5f7fa;
  border-radius: 4px;
}
.info-item {
  font-size: 14px;
}
.info-item strong {
  margin-right: 8px;
  font-weight: bold;
  color: #333333;
}

/* 总用量表格样式优化 */
.allocation-table :deep(.el-table__header) {
  background-color: #f5f7fa;
}
.allocation-table :deep(.el-table__row) {
  height: 50px;
}
</style>
